package com.garen.orm.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.*;
import java.util.Set;

import javax.sql.DataSource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.garen.orm.ConvertColumn;
import com.garen.orm.OrmDBType;
import com.garen.orm.dao.IOrmDao;

@Repository
public class OrmDaoImpl  implements IOrmDao {

	private NamedParameterJdbcTemplate jdbcTemp = null;
	
	public void setDS(DataSource ds){
		//this.setDataSource(ds);
	}
	
	@Override
	public List<String> getTables() {
		String sql = "show tables";
		
		return jdbcTemp.query(sql,new RowMapper<String>() {
			@Override
			public String mapRow(ResultSet arg0, int arg1) throws SQLException {
				return (String)arg0.getObject(1);
			}
		});
	}
	
	
	//获取列详细信息
	@Override
	public Set<ConvertColumn> getColumnInfo(String tableName){
		String sql = "SHOW FULL COLUMNS  FROM " + tableName;
		List<ConvertColumn> list = jdbcTemp.query(sql,
				new ItemMapper());
		return new HashSet<ConvertColumn>(list);
	}
		
	private class ItemMapper implements RowMapper<ConvertColumn> {

        public ConvertColumn mapRow(ResultSet rs, int rowNum) throws SQLException {
        	ConvertColumn obj =new ConvertColumn();
        	String str = null;
        	obj.setColName(rs.getString("field"));
        	obj.setColType(rs.getString("type"));
        	obj.setDefaultValue(rs.getString("default"));//默认值
        	//判断主键
        	str = rs.getString("key");
        	if("PRI".equals(str))
        		obj.setID(true);
        	else
        		obj.setID(false);
        	//是否为空
        	str = rs.getString("null");
        	if("NO".equals(str))
        		obj.setNullable(false);//不能为空
        	else
        		obj.setNullable(true);
        	//判断自增
        	str = rs.getString("Extra");
        	if("auto_increment".equals(str))
        		obj.setAutoIncrement(true);//自增字段
        	else
        		obj.setAutoIncrement(false);
        	obj.setComment(rs.getString("comment"));
        	
        	obj.convert();//类型转换
        	return obj;
        }
    }

	@Override
	public void setOrmdb(OrmDBType ormdb) {
	}	
		

}
